package mideware

import (
	"net/http"
	"strings"
	"wwp.space/NetSim/ndatabase"
	"wwp.space/NetSim/netuser"

	"github.com/gin-gonic/gin"
	"wwp.space/NetSim/wjwt"
)

func VertifyToken() gin.HandlerFunc {

	return func(ctx *gin.Context) {

		if strings.HasPrefix(ctx.Request.URL.Path, "/login") {
			// 跳过中间件逻辑
			ctx.Next()
			return
		}

		token := ctx.Request.Header.Get("net-token")

		if token == "" {
			ctx.JSON(http.StatusForbidden, gin.H{"error": "token为空"})
			ctx.Abort()
			return
		}

		_, maps, err := wjwt.ValidAndGet(token)

		if err != nil {
			ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
			ctx.Abort()
			return
		}
		if name, ok := maps["userId"]; ok {
			ctx.Set("userId", name)
		} else {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "token中没有携带userId"})
			ctx.Abort()
			return
		}

	}
}

func UserCheck() gin.HandlerFunc {

	return func(ctx *gin.Context) {

		var user netuser.User

		user.Account = ctx.Query("account")

		password := ctx.Query("password")
		if user.Account == "" || password == "" {
			ctx.JSON(http.StatusForbidden, gin.H{"error": "账户密码不能为空"})
			ctx.Abort()
			return
		}
		ndatabase.Db.Where("Account = ?", user.Account).Find(&user)
		if user.Password != password {
			ctx.JSON(http.StatusForbidden, gin.H{"error": "密码错误"})
			ctx.Abort()
			return
		}
		ctx.Set("userId", user.ID)
	}
}
